<template>
    <div class="home-container h100">

        <div class="home-left">

            <div class="show-data">
                <div class="data-item" v-for="item in data.showData">
                    <div class="icon">
                        <i :class="'iconfont ' + item.icon"></i>
                    </div>
                    <div class="text">{{ item.title }}</div>
                    <div class="number">{{ item.number }}</div>
                </div>
            </div>

            <div class="funnel">
                <div class="charts-title">
                    <div class="left">
                        <div class="icon"></div>
                        <div class="text">科技成果转化漏斗图</div>
                    </div>
                    <div class="right">
                        <el-radio-group v-model="data.funnelType">
                            <el-radio-button :label="true">需求</el-radio-button>
                            <el-radio-button :label="false">成果</el-radio-button>
                        </el-radio-group>
                        <el-date-picker v-model="data.date" type="monthrange" style="width:160px;margin-left: 10px;" />
                    </div>
                </div>
                <div class="charts-content" ref="funnelDom">
                </div>
            </div>

            <div class="histogram">
                <div class="charts-title">
                    <div class="left">
                        <div class="icon"></div>
                        <div class="text">用户活跃统计</div>
                    </div>
                </div>
                <div class="charts-content" ref="histogramDom">
                </div>
            </div>
        </div>

        <div class="home-right">

            <div class="map">
                <div class="charts-title">
                    <div class="left">
                        <div class="icon"></div>
                        <div class="text">用户活跃分布统计</div>
                    </div>
                </div>
                <div class="charts-content" ref="mapDom">
                </div>
            </div>

            <div class="keywords">
                <div class="charts-title">
                    <div class="left">
                        <div class="icon"></div>
                        <div class="text">平台热搜关键词</div>
                    </div>
                </div>
                <div class="charts-content" ref="cloudDom">
                </div>
            </div>

        </div>
    </div>
</template>

<script setup>
import { reactive, onMounted,onBeforeUnmount, ref, watch ,nextTick} from 'vue';
import { dataDetailApi, demandToAchievementApi, userActiveApi, userAreaApi, keywordsApi } from '@/api/interface/home.js'
import * as echarts from 'echarts'
import 'echarts-wordcloud'
import axios from 'axios'

//倒推一年+补0
const getYearMonthDate = () => {
    const fixZero = v => v >= 10 ? v : '0' + v
    const date = new Date()
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const endDate = year + '-' + fixZero(month) + '-02'
    let startDate
    if (month - 12 < 0) {
        const a = Math.abs(month - 12)
        const lastYearMonth = 12 - a + 1
        startDate = (year - 1) + '-' + fixZero(lastYearMonth) + '-02'
    } else {
        startDate = year + '-01-02'
    }
    return [startDate, endDate]
}

const data = reactive({
    showData: [
        {
            icon: 'icon-zhuanjia',
            title: '专家学者数',
            prop: 'scholars',
            number: '',
        },
        {
            icon: 'icon-daba',
            title: '供需匹配率',
            prop: 'matchRate',
            number: '',
        },
        {
            icon: 'icon-jigouxinxi',
            title: '投资机构数',
            prop: 'invest',
            number: '',
        },
        {
            icon: 'icon-120',
            title: '供需对接数',
            prop: 'join',
            number: '',
        },
        {
            icon: 'icon-nav_keyandangan2',
            title: '科研机构数',
            prop: 'scientific',
            number: '',
        },
        {
            icon: 'icon-paimai',
            title: '累计成交数',
            prop: 'deal',
            number: '',
        },
        {
            icon: 'icon-fuwuzhuce',
            title: '注册用户数',
            prop: 'register',
            number: '',
        },
        {
            icon: 'icon-zu-copy',
            title: '成交总金额(万元)',
            prop: 'sumMoney',
            number: '',
        },
    ],
    date: getYearMonthDate(),
    funnelType: true,
    funnelChart: null,
    lineChart: null,
    mapChart: null,
    cloudChart: null,
    achievementData: {},
    userActiveData: [],
    userAreaData: [],
    keywordsData: [],
})

//图形dom
const funnelDom = ref(null)
const histogramDom = ref(null)
const mapDom = ref(null)
const cloudDom = ref(null)


//平台总览数据
const getDataDetailApi = () => {
    dataDetailApi().then(res => {
        if (res.status === 200) {
            for (let key in res.data) {
                data.showData.find(v => {
                    if (v.prop == key) {
                        v.number = res.data[key]
                    }
                })
            }
        }
    })
}
getDataDetailApi()
//科技成果转化数据 /漏斗图
const getAchievement = async () => {
    await demandToAchievementApi({ startDate: data.date[0], endDate: data.date[1], clickType: data.funnelType ? 'DEMAND' : 'RESULT' }).then(res => {
        if (res.status === 200) {
            data.achievementData = res.data
        }
    })
}
//用户活跃度数据 /折线图
const getUserActive = async () => {
    const date = getYearMonthDate()
    //获取近一年数据
    await userActiveApi({ startDate: date[0], endDate: date[1] }).then(res => {
        if (res.status === 200) {
            data.userActiveData = res.data
        }
    })
}
//用户分布区域统计分析 /地图
const getUserArea = async () => {
    const date = getYearMonthDate()
    await userAreaApi({ startDate: date[0], endDate: date[1] }).then(res => {
        if (res.status === 200) {
            data.userAreaData = res.data
        }
    })
}
//平台用户热搜关键词分析 /词云图
const getKeywords = async () => {
    await keywordsApi().then(res => {
        if (res.status === 200) {
            data.keywordsData = res.data
        }
    })
}




//监听漏斗图类型
watch(() => data.funnelType, (n, o) => {
    initFunnelChart()
})
//监听漏斗图时间范围
watch(() => data.date, (n, o) => {
    initFunnelChart()
})


//初始化渲染图表
onMounted(() => {
    initFunnelChart()
    initLineChart()
    initMap()
    initCloudChart()
})



//漏斗图
const initFunnelChart = async () => {
    await getAchievement()
    data.funnelChart = echarts.init(funnelDom.value);
    // const dataArr = [{ value: data.achievementData.publish, name:`${data.funnelType?'需求':'成果'}发布`, rate: '' }, { value: data.achievementData.match, name: `${data.funnelType?'需求':'成果'}匹配`, rate: data.achievementData.matchRate }, { value: data.achievementData.join, name: `${data.funnelType?'需求':'成果'}对接`, rate: data.achievementData.joinRate }, { value: data.achievementData.success, name: '成交', rate: data.achievementData.successRate }]
    const dataArr = [
        { value: data.funnelType ? 80 : 100, name: `${data.funnelType ? '需求' : '成果'}发布`, rate: '' },
        { value: data.funnelType ?60:60, name: `${data.funnelType ? '需求' : '成果'}匹配`,rate: '10%'},
        { value: data.funnelType ?30:30, name: `${data.funnelType ? '需求' : '成果'}对接`,rate: '10%'},
        { value: data.funnelType ?10:20, name: '成交',rate: '10%'}
    ]
    const colors = ['#f25b5e', '#6A8AEA', '#40B2F3', '#82c870'];
    const lineLength = document.documentElement.clientWidth/9
    const option = {
        title: {
            text: `${data.funnelType?'需求':'成果'}转化率：` + data.achievementData.conversionRate,
            textStyle: {
                fontSize: 16,
                fontWeight: 700
            },
            top: 30,
            left: '44%',
            textAlign: 'center',
        },
        series: [
            {
                mame: 'data',
                type: 'funnel',
                left: '20%',
                right: '10%',
                top: '60px',
                bottom: '0',
                width: '50%',
                maxSize: '100%',
                minSize:'0',
                labelLine: {
                    show: false,
                    emphasis: {
                        show: false,
                    }
                },
                label: {
                    show: false,
                    emphasis: {
                        show: false,
                    }
                },
                data: dataArr
            },
            {
                name: 'left',
                type: 'funnel',
                left: '20%',
                right: '10%',
                top: '60px',
                bottom: '0',
                width: '50%',
                maxSize: 0,
                minSize: 0,
                color: colors,
                z: -1,
                labelLine: {
                    length: lineLength,
                    lineStyle: {
                        type: 'dotted',
                        width: 1.5,
                    }
                },
                label: {
                    normal: {
                        position: 'left',
                        color: '#333',
                    }
                },
                data: dataArr
            },
            {
                name: 'right',
                type: 'funnel',
                left: '20%',
                right: '10%',
                top: '60px',
                bottom: '0',
                width:'50%',
                minSize: 0,
                maxSize: 0,
                color: colors,
                z: -1,
                labelLine: {
                    length: lineLength,
                    lineStyle: {
                        type: 'dotted',
                        width: 1.5,
                    }
                },
                label: {
                    normal: {
                        position: 'right',
                        color: '#333',
                        formatter: function (d) {
                            var ins = `${d.value}  ${d.data.rate ? '{aa|}' : ''} ${d.data.rate ? '丢失' : ''} ${d.data.rate}`;
                            return ins

                        },
                        rich: {
                            aa: {
                                backgroundColor: {
                                    image: '/src/assets/img/xiajiantou.png',
                                    padding: [1, 2, 3, 4],
                                },
                                width: 8,
                                height: 15,
                                align: 'center',
                                padding: [0, 0, 0, 0]
                            },
                        }
                    }
                },
                data: dataArr
            },

        ]
    };
    data.funnelChart.setOption(option)
}
//折线图
const initLineChart = async() => {
    await getUserActive()
    const dataArr = data.userActiveData.map(v => v.doc_count)
    const xList = data.userActiveData.map(v => v.key_as_string)
     data.lineChart = echarts.init(histogramDom.value)
    const option = {
        grid: {
            left: '10px',
            right: '30px',
            bottom: '0',
            top: '40px',
            containLabel: true
        },
        xAxis: [
            {
                type: 'category',
                boundaryGap: false,
                data: xList
            }
        ],
        yAxis: [
            {
                type: 'value'
            }
        ],
        series: [
            {
                name: 'Email',
                type: 'line',
                showSymbol: false,
                lineStyle: {
                    width: 2,
                    color: '#00A2FF'
                },
                areaStyle: {
                    opacity: 0.8,
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        {
                            offset: 0,
                            color: 'rgba(0, 162, 255, 0.2)'
                        },
                        {
                            offset: 1,
                            color: 'rgba(0, 162, 255, 0)'
                        }
                    ])
                },
                emphasis: {
                    focus: 'series'
                },
                data: dataArr
            },
        ]
    }
    data.lineChart.setOption(option);
}
//地图
const initMap = async () => {
    await getUserArea()//地图
    data.mapChart = echarts.init(mapDom.value);
    data.mapChart.showLoading();
    const china = await axios.get(`mapJSON/china.json`).then(res => {
        return res.data
    })
    
    data.mapChart.hideLoading();
    echarts.registerMap('china', china);
    const option = {
        visualMap: {
            pieces: [{
                gt: 30000,
                color: "#6A8AEA"
            }, {
                lt: 29999,
                gt: 20000,
                color: "#AFBDF5"
            }, {
                lt: 19999,
                gt: 10000,
                color: "#CED8F7"
            }, {
                lt: 9999,
                gt: 1000,
                color: "#CED8F7"
            }, {
                lt: 1000,
                color: "#f1f1f1"
            }],
        },
        geo: {
            name: 'china',
            map: "china",
            type: 'map',
            mapType: 'china',
            zoom: 1.1,
            top: 50,
            itemStyle: {
                normal: {
                    borderColor: '#BFC6E0',
                    borderWidth: 1.5,
                    areaColor: "#fff"
                },
                emphasis: {
                    areaColor: "#f2d5ad",
                    borderWidth: 0
                }
            }
        },
        series: [{
            type: "map",
            geoIndex: 0,
            data: data.userAreaData.map(v => {
                v.name = v.key
                v.value = v.doc_count
                return v
            })
        }]
    };
    data.mapChart.setOption(option);
}
//词云+动态大小算法
const initCloudChart = async () => {
    await getKeywords()//词云图
    class Obj {
        constructor(name, value, color, symbolSize, fontSize) {
            this.name = name,
                this.value = value,
                this.itemStyle = {
                    color: color
                },
                this.symbolSize = symbolSize,
                this.label = {
                    color: '#333',
                    fontSize: fontSize
                }
        }
    }
    const colorList = ['#6A8AEA', '#A891FD', '#E192FF', '#FFBD91', '#E8ECF8',]
    const fontSizeList = [16, 14, 12, 11, 10]
    const symbolSizeList = [60, 50, 40, 30, 20]

    const max = Math.max(...data.keywordsData.map(v => v.doc_count))
    let sortArr = []
    const ave = max / fontSizeList.length
    for (let i = 0; i < fontSizeList.length; i++) {
        sortArr.unshift(Math.ceil(ave * i))
    }
    let dataArr = []
    data.keywordsData.forEach(v => {
        for (let k = 0; k < sortArr.length; k++) {
            if (v.doc_count <= sortArr[k] && v.doc_count > sortArr[k + 1]) {
                let a = new Obj(v.key, v.doc_count, colorList[k], symbolSizeList[k], fontSizeList[k])
                dataArr.push(a)
                break
            }
        }
    })

    data.cloudChart = echarts.init(cloudDom.value);
    const option = {
        series: [
            {
                type: 'graph',
                layout: 'force',
                force: {
                    repulsion: 50,
                    edgeLength: 10
                },
                roam:false,
                // roam: 'scale',
                label: {
                    show: true,
                    fontSize: 12
                },
                data: dataArr
            }
        ]
    }
    data.cloudChart.setOption(option);
}

</script>

<style lang="scss" scoped>
.home-container {
    display: flex;
    background-color: #f0f3fa;
    overflow-y: scroll;
    width: 100%;
    .home-left,
    .home-right {
        width: 49.5%;
    }
    .home-left {
        margin-right: 1%;
        .show-data {
            display: flex;
            padding: 20px;
            margin-bottom: 10px;
            flex-wrap: wrap;
            justify-content: space-between;
            align-content: space-between;
            height: 290px;
            width: 100%;
            .data-item {
                display: flex;
                align-items: center;
                height: 22%;
                width: 49%;
                background-color: #F3F7FF;
                border-radius: 4px;
                .icon {
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    margin-left: 10px;
                    height: 30px;
                    width: 30px;
                    color: #fff;
                    border-radius: 4px;
                    background-color: #00A2FF;
                }
                .text {
                    width: 42%;
                    font-size: 14px;
                    font-weight: 700;
                    margin-left: 10px;
                }
                .number {
                    font-size: 18px;
                    font-weight: 700;
                    margin-right: 40px;
                }
            }
        }

        .funnel,
        .histogram {
            height: 380px;
            margin-bottom: 10px;
            padding: 20px;
            box-sizing: border-box;
        }

        .histogram {
            margin-bottom: 0;
        }
    }

    .home-right {
        .map {
            margin-bottom: 10px;
            height: 680px;
        }

        .keywords {
            height: 380px;
        }
    }

    .funnel,
    .show-data,
    .histogram,
    .map,
    .keywords {
        background-color: #fff;
        border-radius: 8px;
        box-sizing: border-box;
    }

    .funnel,
    .histogram,
    .map,
    .keywords {
        display: flex;
        flex-direction: column;
        padding: 20px;

        .charts-title {
            display: flex;
            justify-content: space-between;
            align-items: center;

            .left {
                display: flex;

                // flex: 3;
                .icon {
                    width: 6px;
                    height: 18px;
                    background-color: #00A2FF;
                    margin-right: 6px;
                }

                .text {
                    font-weight: 700;
                    font-size: 18px;
                }
            }

            .right {
                display: flex;

                :deep(.el-radio-button__inner) {
                    font-size: 12px;
                }

                :deep(.el-range-input) {
                    font-size: 12px;
                }
            }
        }

        .charts-content {
            flex: 1;
        }
    }
}
</style>